<?php
/**
 * MerchantController class.
 * MerchantController is the controller for business portal.
 * 
 * It used for all functions of Merchant.
 * 
 * Yawii Business 版权所有 @ 2012.
 */
class MerchantController extends Controller
{
	/**
	 * @return array action filters
	 */
	public function filters() {
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}
	
	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules() {
		return array(
			array('allow', // allow authenticated user to perform below actions
				'users'=>array('@'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}
	
	public function actionIndex()
	{
		$model = $this->loadModel(Yii::app()->user->id);
		$model->setScenario('profile');
		
		//fetch menu and lunch offer
		$week_days = Yii::app()->request->getQuery('week', date('N'));	//get week day number: 1 (for Monday) - 7 (for Sunday)
		if ($week_days < 1 or $week_days > 7) $week_days = date('N');
		
		$connection = Yii::app()->db;
		//1. fetch menu
		$sql_menu = 'SELECT id, url_picture, content, title,
			UNIX_TIMESTAMP(insert_timestamp) AS uts_insert, UNIX_TIMESTAMP(update_timestamp) AS uts_update
			FROM tbl_merchant_lunch_menu
			WHERE id_merchant=:id_merchant AND week_days LIKE :week_days';
		$params_menu = array('id_merchant'=>(int)Yii::app()->user->id, 'week_days'=>"%{$week_days}%");
		$command = $connection->createCommand($sql_menu);
		$menu_rows = $command->queryAll(true, $params_menu);
		
		//2. fetch 
		$sql_special = 'SELECT id, url_picture, content,
			show_price, price, value, 100-(price/value * 100) AS discount,
			show_hours, start_hour, end_hour, week_days,
			UNIX_TIMESTAMP(start_date) AS uts_start_date, UNIX_TIMESTAMP(end_date) AS uts_end_date
			FROM tbl_merchant_special
			WHERE id_merchant=:id_merchant AND week_days LIKE :week_days
			AND trash=0 AND status=1 AND start_date<NOW() AND end_date>NOW()';
		$command = $connection->createCommand($sql_special);
		$special_rows = $command->queryAll(true, array('id_merchant'=>(int)Yii::app()->user->id, 'week_days'=>"%{$week_days}%"));
		
		//3. fetch merchant tags
		$sql_tags = 'SELECT cuisine_style, cuisine_type, meal_served, payment_options, service_languages, 
			alcohol_license, dining_ambience, car_parking, additional_details
			FROM tbl_merchant_tags WHERE id_merchant=:id_merchant';
		$command = $connection->createCommand($sql_tags);
		$tags_row = $command->queryRow(true, array('id_merchant'=>(int)Yii::app()->user->id));
		
		//4. fetch merchant's open hours
		$sql_hours = 'SELECT week_no, open_hour, close_hour FROM tbl_merchant_open_hours
			WHERE id_merchant=:id_merchant ORDER BY week_no ASC';
		$command = $connection->createCommand($sql_hours);
		$hours = $command->queryAll(true, array('id_merchant'=>Yii::app()->user->id));
		$connection->active = false;
		
		$this->render('index', array(
			'model' => $model,
			'menu_rows' => $menu_rows,
			'special_rows' => $special_rows,
			'week_days' => $week_days,
			'tags' => $tags_row,
			'hours' => $hours,
		));
	}
	
	public function actionAccount()
	{
		$model = $this->loadModel(Yii::app()->user->id);
		$model->setScenario('account');
		
		// if it is ajax validation request
		if (isset($_POST['ajax']) && $_POST['ajax'] === 'merchant-form') {
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}

		// collect user input data
		if (isset($_POST['MerchantForm'])) {
			$model->attributes = $_POST['MerchantForm'];
			$model->new_password = $_POST['MerchantForm']['new_password'];
			if ($_POST['MerchantForm']['new_email'] == $model->email) {
				$model->new_email = $model->email;
			} else {
				$model->new_email = $_POST['MerchantForm']['new_email'];
				
				//check the new email
				$connection = Yii::app()->db;
				$command = $connection->createCommand('SELECT id FROM tbl_merchant_account WHERE email=:email');
				$row = $command->queryRow(true, array('email' => $model->new_email));
				$connection->active = false;
				if (!empty($row)) {
					$model->addError('new_email', BUtils::T('duplicate_email_error_msg'));
					// display the login form
					$this->render('account', array('model' => $model));
					Yii::app()->end();
				}
			}
			
			// validate user input and redirect to the previous page if valid
			if ($model->validate()) {
				$pasword_in_db = BUtils::Hash32(md5($model->new_password));
				$connection = Yii::app()->db;
				$command = $connection->createCommand('UPDATE tbl_merchant_account SET email=:email, password=:password, update_timestamp=NOW() WHERE id=:id');
				$command->execute(array('id' => Yii::app()->user->id, 'email' => $model->new_email, 'password' => $pasword_in_db));
				$connection->active = false;
				
				Yii::app()->user->setFlash('account', BUtils::T('saved_successfully_lbl'));
				$this->refresh();
			}
		}
		
		// display the login form
		$this->render('account', array('model' => $model));
	}

	public function actionProfile()
	{
		$model = $this->loadModel(Yii::app()->user->id);
		$model->setScenario('profile');
		
		if (isset($_POST['ajax']) && $_POST['ajax'] === 'merchant-form') {
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
		
		// collect user input data
		if (isset($_POST['MerchantForm'])) {
			//save open hours
			if (!empty($_POST['business_hours'])) {
				$sql_hours_delete = 'DELETE FROM tbl_merchant_open_hours WHERE id_merchant=:id_merchant';
				$sql_hours_insert = 'INSERT INTO tbl_merchant_open_hours(id_merchant, week_no, open_hour, close_hour) VALUES (:id_merchant, :week_no, :open_hour, :close_hour)';
				$connection = Yii::app()->db;
				$command = $connection->createCommand($sql_hours_delete);
				$command->execute(array('id_merchant'=>Yii::app()->user->id));
				$command = $connection->createCommand($sql_hours_insert);
				$hittedWeek = array();
				foreach ($_POST['business_hours'] as $v) {
					$aTemp = explode(',', $v);
					if (false === array_search($aTemp[0], $hittedWeek)) {
						$params = array(
							'id_merchant' => Yii::app()->user->id,
							'week_no' => $aTemp[0],
							'open_hour' => $aTemp[1],
							'close_hour' => $aTemp[2],
						);
						$command->execute($params);
						$hittedWeek[] = $aTemp[0];
					}
				}
				$connection->active = false;
			}
			
			$model->attributes = $_POST['MerchantForm'];
			
			//set the address
			if (!empty($_POST['MerchantForm']['address'])) {
				$locArray = explode(',', $_POST['MerchantForm']['address']);
				if (count($locArray) > 0) {
					$model->address = trim($locArray[0]);
				}
			}
			
			//set unsafe values which are specified by rules method of MerchantForm class
			$model->url_site = $_POST['MerchantForm']['url_site'];
			if (!empty($model->address)) {
				$model->latitude = $_POST['MerchantForm']['latitude'];
				$model->longitude = $_POST['MerchantForm']['longitude'];
			}
			$model->country_code = $_POST['MerchantForm']['country_code'];
			$model->currency_code = 'EUR';
			$model->brief = $_POST['MerchantForm']['brief'];
			$model->average_price = ($_POST['MerchantForm']['average_price'] < 1) ? new CDbExpression('NULL') : $_POST['MerchantForm']['average_price'];
			$model->update_timestamp = new CDbExpression('NOW()');	//update AR
			
			// validate user input and redirect to the previous page if valid
			if ($model->save()) {
				//change the category_key of this session
				Yii::app()->user->setState('category_key', $model->category_key);
				Yii::app()->user->setState('name', $model->name);
				Yii::app()->user->setState('address', $model->address);
				Yii::app()->user->setState('biz_area', $model->biz_area);
				Yii::app()->user->setState('postcode', $model->postcode);
				Yii::app()->user->setState('city', $model->city);
				
				$message = '{"success":"'.BUtils::T('profile_save_done_lbl').'"}';
			} else {
				$message = CActiveForm::validate($model);
				
				//trace error
				Yii::log('Merchant '.Yii::app()->user->id.' profile saving is failed! ' . json_encode($model->errors),
					CLogger::LEVEL_ERROR, 'system.web.server');
			}
			
			if (Yii::app()->request->isAjaxRequest) {
				echo $message;
				Yii::app()->end();
			} else {
				Yii::app()->user->setFlash('profile', BUtils::T('profile_save_done_lbl'));
				$this->refresh();
				
				//trace error
				Yii::log('Merchant '.Yii::app()->user->id.' is using the non-ajax submit.',
					CLogger::LEVEL_ERROR, 'system.web.client');
			}
		}
		
		//2. get merchant's open hours
		$sql_hours = 'SELECT week_no, open_hour, close_hour FROM tbl_merchant_open_hours
			WHERE id_merchant=:id_merchant ORDER BY week_no ASC';
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_hours);
		$hours = $command->queryAll(true, array('id_merchant'=>Yii::app()->user->id));
		
		//3. get merchant's tags
		$sql_tags = 'SELECT cuisine_style, cuisine_type, meal_served, payment_options, service_languages, 
			alcohol_license, dining_ambience, car_parking, additional_details
			FROM tbl_merchant_tags WHERE id_merchant=:id_merchant';
		$command = $connection->createCommand($sql_tags);
		$tags = $command->queryRow(true, array('id_merchant'=>Yii::app()->user->id));
		$connection->active = false;

		$this->render('profile', array(
			'model' => $model,
			'tags' => $tags,
			'hours' => $hours
		));
	}
	
	/**
	 * Feature page 
	 */
	public function actionFeature()
	{
		$model = $this->loadModel(Yii::app()->user->id);
		$model->setScenario('profile');
		
		//2. fetch merchant tags
		$sql_tags = 'SELECT cuisine_style, cuisine_type, meal_served, payment_options, service_languages, 
			alcohol_license, dining_ambience, car_parking, additional_details
			FROM tbl_merchant_tags WHERE id_merchant=:id_merchant';
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_tags);
		$tags = $command->queryRow(true, array('id_merchant'=>Yii::app()->user->id));
		
		//3. fetch merchant's open hours
		$sql_hours = 'SELECT week_no, open_hour, close_hour FROM tbl_merchant_open_hours
			WHERE id_merchant=:id_merchant ORDER BY week_no ASC';
		$command = $connection->createCommand($sql_hours);
		$hours = $command->queryAll(true, array('id_merchant'=>Yii::app()->user->id));
		$connection->active = false;

		if (Yii::app()->user->getState('category_key') == 'restaurants') {
			$page = 'feature_restaurants';
		} else $page = 'feature';
		$this->render($page, array(
			'model' => $model,
			'tags' => $tags,
			'hours' => $hours
		));
	}
	
	/**
	 * Save tags with AJAX.
	 */
	public function actionSaveTags()
	{
		//get post data
		$sql_insert = 'INSERT INTO tbl_merchant_tags(';
		$sql_insert_value = ' VALUES(';
		$params = array();
		foreach ($_POST as $key => $value) {
			if (!empty($value)) {
				if (is_array($value)) {
					$params[$key] = implode(',', $_POST[$key]);
					$sql_insert .= "{$key}, ";
					$sql_insert_value .= ":{$key}, ";
				} elseif ($key === 'alcohol_license') {
					$params[$key] = $_POST[$key];
					$sql_insert .= "{$key}, ";
					$sql_insert_value .= ":{$key}, ";
				}
			}
		}
		$sql_insert .= 'id_merchant)';
		$sql_insert_value .= ":id_merchant)";
		$params['id_merchant'] = Yii::app()->user->id;
		
		//print_r(array($sql_insert, $params)); exit;
		
		$sql_delete = 'DELETE FROM tbl_merchant_tags WHERE id_merchant=:id_merchant';
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_delete);
		$command->execute(array('id_merchant'=>Yii::app()->user->id));
		$command = $connection->createCommand($sql_insert . $sql_insert_value);
		$command->execute($params);
		$connection->active = false;
		
		if (Yii::app()->request->isAjaxRequest) {
			echo '{"success":"'.BUtils::T('detail_features_save_done_msg').'"}';
		} else {
			Yii::app()->request->redirect(Yii::app()->createUrl($this->id . '/profile'));
		}
	}
	
	public function actionGallery() {
		//select all photos
		$connection = Yii::app()->db;
		$sql_gallery = 'SELECT g.id, g.url_picture, g.title, g.type, g.id_user, UNIX_TIMESTAMP(g.create_time) AS ts_create_time,
			u.username, u.name
			FROM tbl_merchant_gallery g
			LEFT JOIN tbl_user_account u ON u.id=g.id_user
			WHERE id_merchant=:id_merchant
			ORDER BY create_time DESC';
		$command = $connection->createCommand($sql_gallery);
		$gallery_rows = $command->queryAll(true, array('id_merchant'=>Yii::app()->user->id));
		$connection->active = false;
		
		$this->render('gallery', array('gallery_rows' => $gallery_rows));
	}
	
	/**
	 * Insert menu picture with AJAX 
	 */
	public function actionUploadGallery()
	{
		//set folder
		$saved_folder = BUtils::GetUploadingFolder(Yii::app()->user->id);
		$url_folder = BUtils::GetUploadingUrl(Yii::app()->user->id);
		
		Yii::import("ext.EAjaxUpload.qqFileUploader");
		$prefix = Yii::app()->request->getParam('prefix', null);
		$allowedExtensions = array("jpg","jpeg","gif","png");
		$sizeLimit = 8 * 1024 * 1024;
		$uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
		$result = $uploader->handleUpload($saved_folder, uniqid($prefix));
		unset($uploader);
		
		//thumb picture
		$thumb = 'thumb_' . $result['filename'];
		//thumb picture 2
		$thumb_200h = 'thumb_200h_' . $result['filename'];
		
		try {
			//resize picture to 640 x 640.
			Yii::import('ext.iwi.Iwi');
			$picture = new Iwi($saved_folder . $result['filename']);
			$minSize = $picture->getMinSize();
			if ($minSize > 640) $minSize = 640;
			$width = $minSize;
			$height = $picture->getRatio() * $width;
			$picture->adaptive($minSize, $height);
			$picture->save($saved_folder . $result['filename']);
			// 120x120
			$picture->adaptive(120, 120);
			$picture->save($saved_folder . $thumb);
			// 283x200
			$picture->adaptive(283, 200);
			$picture->save($saved_folder . $thumb_200h);
			unset($picture);
		} catch (Exception $ex) {
			echo '{"error" : "Photo cannot be saved!"}';
			Yii::app()->end();
		}
		
		//delete the original picture (not delete, just keep them there)
		
		//insert into menu table
		$connection = Yii::app()->db;
		$sql_photo = 'INSERT INTO tbl_merchant_gallery (id_merchant, url_picture, type) VALUES (:id_merchant, :url_picture, 0)';
		$command = $connection->createCommand($sql_photo);
		$command->execute(array('id_merchant'=>Yii::app()->user->id, 'url_picture'=>$url_folder . $thumb));
		
		$command = $connection->createCommand('select id FROM tbl_merchant_gallery WHERE url_picture=:url_picture');
		$row = $command->queryRow(true, array('url_picture'=>$url_folder . $thumb));
		$connection->active = false;
		
		//add id
		if (empty($row['id'])) {
			echo '{"error" : "Photo cannot be saved!"}';
		} else {
			$result['id'] = $row['id'];
			$result['url_picture'] = $url_folder . $result['filename'];
			echo htmlspecialchars(json_encode($result), ENT_NOQUOTES);
		}
	}
	
	/**
	 * Delete photo of gallery.
	 * @param int $id the id of tbl_merchant_gallery.
	 * @throws CHttpException
	 */
	public function actionDeleteGallery($id) {
		if (empty($id)) {
			throw new CHttpException(404, 'The parameter id is missing!');
		}
		
		$sql_delete = 'DELETE FROM tbl_merchant_gallery WHERE id_merchant=:id_merchant AND id=:id';
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_delete);
		$command->execute(array('id_merchant'=>Yii::app()->user->id, 'id'=>$id));
		$connection->active = false;

		//delete picture file
		$url_picture = Yii::app()->request->getParam('url');
		if (!empty($url_picture)) {
			//find file name
			$tmp = explode('/', $url_picture);
			$thumbName = array_pop($tmp);
			$uploadPath = $saved_folder = BUtils::GetUploadingFolder(Yii::app()->user->id);
			@unlink($uploadPath . $thumbName);
			$thumbName200 = str_replace('thumb_', 'thumb_200h_', $thumbName);
			@unlink($uploadPath . $thumbName200);
			$fileName = str_replace('thumb_', '', $thumbName);
			@unlink($uploadPath . $fileName);
		}
	}
	
	/**
	 * Insert logo picture with AJAX.
	 * 160 x 160 (but keep aspect ratio)
	 */
	public function actionUploadLogo()
	{
		//set folder
		$saved_folder = BUtils::GetUploadingFolder(Yii::app()->user->id);
		$url_folder = BUtils::GetUploadingUrl(Yii::app()->user->id);
		
		Yii::import("ext.EAjaxUpload.qqFileUploader");
		$allowedExtensions = array("jpg","jpeg","gif","png");//array("jpg","jpeg","gif","exe","mov" and etc...
		$sizeLimit = 8 * 1024 * 1024;	// maximum file size in bytes
		$uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
		$result = $uploader->handleUpload($saved_folder, 'logo_m_' . Yii::app()->user->id, true);
		unset($uploader);
		
		//resize logo picture to 160 x 160 size:
		Yii::import('ext.iwi.Iwi');
		$picture = new Iwi($saved_folder . $result['filename']);
		$picture->adaptive(160, 160);
		$picture->save($saved_folder . $result['filename']);
		unset($picture);
		
		//delete the original logo picture (not delete, just keep them there)
		
		//insert into menu table
		$sql_menu = 'UPDATE tbl_merchant_account SET url_logo=:url_logo WHERE id=:id';
		$params_menu = array('id'=>Yii::app()->user->id, 'url_logo'=>$url_folder . $result['filename']);
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_menu);
		$command->execute($params_menu);
		$connection->active = false;
		$result['url_logo'] = $url_folder . $result['filename'] . '?t=' . time();
		echo htmlspecialchars(json_encode($result), ENT_NOQUOTES);
	}
	
	/**
	 * Insert url_offer_img picture with AJAX.
	 * 96x96 + 640x320
	 */
	public function actionUploadOfferImage()
	{
		//set folder
		$saved_folder = BUtils::GetUploadingFolder(Yii::app()->user->id);
		$url_folder = BUtils::GetUploadingUrl(Yii::app()->user->id);
		
		$file_postfix = time() . rand(100, 999);
		
		Yii::import("ext.EAjaxUpload.qqFileUploader");
		$allowedExtensions = array("jpg","jpeg","gif","png");//array("jpg","jpeg","gif","exe","mov" and etc...
		$sizeLimit = 8 * 1024 * 1024;	// maximum file size in bytes
		$uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
		$result = $uploader->handleUpload($saved_folder, 'offer_m_' . $file_postfix, true);
		unset($uploader);
		
		//set thumb
		$thumb = 'thumb_' . $result['filename'];
		
		//resize offer picture to 640 x 360 size:
		Yii::import('ext.iwi.Iwi');
		$picture = new Iwi($saved_folder . $result['filename']);
		// resize to 640x360: 16:9
		$picture->adaptive(640, 360);
		$picture->save($saved_folder . $result['filename']);
		// resize to 108x108
		$picture->adaptive(192, 108);
		$picture->crop(108, 108);
		$picture->save($saved_folder . $thumb);
		
		unset($picture);
		
		//insert into menu table
		$sql_menu = 'UPDATE tbl_merchant_account SET url_offer_img=:url_offer_img WHERE id=:id';
		$params_menu = array('id'=>Yii::app()->user->id, 'url_offer_img'=>$url_folder . $thumb);
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_menu);
		$command->execute($params_menu);
		$connection->active = false;
		$result['url_offer_img'] = $url_folder . $result['filename'] . '?t=' . time();
		echo htmlspecialchars(json_encode($result), ENT_NOQUOTES);
	}
	
	/**
	 * Insert menu picture with AJAX 
	 */
	public function actionUploadMenu()
	{
		//set folder
		$saved_folder = BUtils::GetUploadingFolder(Yii::app()->user->id);
		$url_folder = BUtils::GetUploadingUrl(Yii::app()->user->id);
		
		Yii::import("ext.EAjaxUpload.qqFileUploader");
		$prefix = Yii::app()->request->getParam('prefix', null);
		$allowedExtensions = array("jpg","jpeg","gif","png");
		$sizeLimit = 8 * 1024 * 1024;
		$uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
		$result = $uploader->handleUpload($saved_folder, uniqid($prefix));
		unset($uploader);
		
		//resize picture to A4 size: 210 x 297mm (945 x 1336)
		Yii::import('ext.iwi.Iwi');
		$picture = new Iwi($saved_folder . $result['filename']);
		$picture->adaptive(945, 1336);
		$picture->save($saved_folder . $result['filename']);
		unset($picture);
		
		//delete the original picture (not delete, just keep them there)
		
		//insert into menu table
		$connection = Yii::app()->db;
		$sql_menu = 'INSERT INTO tbl_merchant_lunch_menu (id_merchant, url_picture) VALUES (:id_merchant, :url_picture)';
		$params_menu = array('id_merchant'=>Yii::app()->user->id, 'url_picture'=>$url_folder . $result['filename']);
		$command = $connection->createCommand($sql_menu);
		$command->execute($params_menu);
		
		$command = $connection->createCommand('select id FROM tbl_merchant_lunch_menu WHERE url_picture=:url_picture');
		$row = $command->queryRow(true, array('url_picture'=>$url_folder . $result['filename']));
		$connection->active = false;
		
		//add id
		if (empty($row['id'])) {
			echo '{"error" : "Menu cannot be saved!"}';
		} else {
			$result['id_menu'] = $row['id'];
			$result['url_picture'] = $url_folder . $result['filename'];
			echo htmlspecialchars(json_encode($result), ENT_NOQUOTES);
		}
	}
	
	/**
	 * Update menu content
	 * POST
	 *     menuForm[id]	100025
	 *     menuForm[title]	Quick Menu for lunch
	 *     menuForm[weekdays][]	1 2 3
	 */
	public function actionSaveMenu() {
		$menuId = Yii::app()->request->getQuery('id', 0);
		if ($menuId < 1) {
			echo $menuId;
			Yii::app()->end();
		}
		$form = Yii::app()->request->getPost('menuForm', null);
		if (!empty($form) and $form['id'] > 0 and !empty($form['week_days'])) {
			$connection = Yii::app()->db;
			$sql_menu = 'UPDATE tbl_merchant_lunch_menu SET week_days=:week_days, update_timestamp=NOW() WHERE id_merchant=:id_merchant AND id=:id';
			$params_menu = array(
				'week_days'=> implode(',', $form['week_days']),
				'id_merchant' => Yii::app()->user->id, 'id' => $menuId);
			$command = $connection->createCommand($sql_menu);
			$command->execute($params_menu);
			$connection->active = false;
		}
		echo date('Y-m-d H:i:s');
	}
	
	/**
	 * Delete menu data and its picture file
	 * GET or POST
	 *     id 100025
	 *     url /business/upload/menu_10001_4faed98d51947.jpg 
	 */
	public function actionDeleteMenu() {
		$menuId = Yii::app()->request->getParam('id', 0);
		if ($menuId > 0) {
			$connection = Yii::app()->db;
			$sql_menu = 'DELETE FROM tbl_merchant_lunch_menu WHERE id_merchant=:id_merchant AND id=:id';
			$params_menu = array('id_merchant'=>Yii::app()->user->id, 'id'=>$menuId);
			$command = $connection->createCommand($sql_menu);
			$command->execute($params_menu);
			$connection->active = false;
			
			//delete picture file
			$url_picture = Yii::app()->request->getParam('url');
			if (!empty($url_picture)) {
				@unlink(Yii::app()->basePath . '/../..' . $url_picture);
			}
		} else {
			
		}
	}
	
	/**
	 * Delete menu data and its picture file
	 * GET or POST
	 *     id 100025
	 *     url /business/upload/menu_10001_4faed98d51947.jpg 
	 */
	public function actionReportBonus() {
		
		//statistic all merchants and downloads and redeem numbers
		/* SELECT d.device_token, d.device_type, d.id_user, d.insert_time, r.redeemed_time, r.id_special, s.id_merchant
FROM tbl_user_device_settings d
INNER JOIN tbl_merchant_special_redeem r ON r.device_token = d.device_token
INNER JOIN tbl_merchant_special s ON s.id = r.id_special
WHERE r.redeemed_time IS NOT NULL AND r.redeemed_time<DATE_ADD(d.insert_time, INTERVAL 1 HOUR)
		 */
		//list the redeemed data for this merchants with the device insert time is shorter than 1 hours.
		$sql_bonus = 'SELECT d.device_token, d.device_type, d.id_user, d.insert_time, r.redeemed_time, r.id_special, s.id_merchant, s.discount
			FROM tbl_user_device_settings d
			INNER JOIN tbl_merchant_special_redeem r ON r.device_token=d.device_token
			INNER JOIN tbl_merchant_special s ON s.id=r.id_special
			WHERE s.id_merchant=:id_merchant AND r.redeemed_time>:start_date AND r.redeemed_time<:end_date
			  AND r.redeemed_time IS NOT NULL AND r.redeemed_time<DATE_ADD(d.insert_time, INTERVAL 1 HOUR)
			ORDER BY r.redeemed_time DESC ';
		$params = array(
			':id_merchant' => (int)Yii::app()->user->id,
			':start_date' => '2013-04-01 00:00:00',
			':end_date' => '2013-08-31 23:59:59',
		);
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_bonus);
		$rows = $command->queryAll(true, $params);
		$connection->active = false;
		
		$detail = Yii::app()->request->getParam('detail');
		
		if (empty($detail)) {
			if (Yii::app()->request->isAjaxRequest) {
				//give a total number x 1.00;
				echo json_encode(array(
					count($rows)
				));
			} else {
				throw new CHttpException(404, 'The requested page does not exist.');
			}
		} else {
			if (Yii::app()->request->isAjaxRequest) {
				$this->renderPartial('_bonus', array('rows' => $rows));
			} else {
				$this->render('_bonus', array('rows' => $rows));
			}
		}
	}
	
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	protected function loadModel($id)
	{
		$model = MerchantForm::model()->findByPk($id);
		if ($model===null)
			throw new CHttpException(404, 'The requested page does not exist.');
		return $model;
	}
}